from django.shortcuts import render, get_object_or_404, redirect
from django.http import JsonResponse
from django.urls import reverse_lazy
from django.views.generic import ListView, CreateView, UpdateView, DeleteView, DetailView, View
from django.contrib.auth.mixins import LoginRequiredMixin
from django.contrib import messages
from django.utils import timezone
from django.db.models import Q
from django.views.decorators.csrf import csrf_exempt
from django.utils.decorators import method_decorator
from .models import Article, Tag


# 文章列表视图
class ArticleListView(ListView):
    model = Article
    template_name = "ip_analysis/article_list.html"
    context_object_name = "articles"
    paginate_by = 10
    
    def get_queryset(self):
        # 只显示已发布的文章
        queryset = Article.objects.filter(status="published", publish_date__lte=timezone.now())
        
        # 按置顶和发布时间排序
        queryset = queryset.order_by("-is_sticky", "-publish_date")
        
        # 支持按标签筛选
        tag = self.request.GET.get("tag")
        if tag:
            queryset = queryset.filter(tags__name=tag)
        
        # 支持搜索
        search = self.request.GET.get("search")
        if search:
            queryset = queryset.filter(
                Q(title__icontains=search) |
                Q(summary__icontains=search) |
                Q(content__icontains=search)
            )
        
        return queryset
    
    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        # 添加所有标签供筛选
        context["tags"] = Tag.objects.filter(is_active=True)
        # 添加搜索关键词
        context["search_query"] = self.request.GET.get("search", "")
        context["selected_tag"] = self.request.GET.get("tag", "")
        return context


# 文章详情视图
class ArticleDetailView(DetailView):
    model = Article
    template_name = "ip_analysis/article_detail.html"
    context_object_name = "article"
    
    def get_queryset(self):
        # 只显示已发布的文章
        return Article.objects.filter(status="published", publish_date__lte=timezone.now())
    
    def get_object(self, queryset=None):
        article = super().get_object(queryset)
        # 增加阅读量
        article.view_count += 1
        article.save(update_fields=["view_count"])
        return article
    
    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        # 获取相关文章（基于相同标签）
        article = self.object
        context["related_articles"] = Article.objects.filter(
            tags__in=article.tags.all(),
            status="published",
            publish_date__lte=timezone.now()
        ).exclude(id=article.id).distinct()[:5]
        return context


# 后台文章管理列表
class ArticleAdminListView(LoginRequiredMixin, ListView):
    model = Article
    template_name = "ip_analysis/article_admin_list.html"
    context_object_name = "articles"
    paginate_by = 20
    
    def get_queryset(self):
        queryset = Article.objects.all()
        
        # 支持按状态筛选
        status = self.request.GET.get("status")
        if status:
            queryset = queryset.filter(status=status)
        
        # 支持搜索
        search = self.request.GET.get("search")
        if search:
            queryset = queryset.filter(
                Q(title__icontains=search) |
                Q(summary__icontains=search)
            )
        
        return queryset.order_by("-is_sticky", "-created_at")
    
    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context["search_query"] = self.request.GET.get("search", "")
        context["selected_status"] = self.request.GET.get("status", "")
        return context


# 创建文章视图
class ArticleCreateView(LoginRequiredMixin, CreateView):
    model = Article
    template_name = "ip_analysis/article_form.html"
    fields = ["title", "slug", "summary", "content", "tags", "is_sticky",
              "meta_title", "meta_description", "meta_keywords"]
    
    def form_valid(self, form):
        form.instance.created_by = self.request.user
        messages.success(self.request, "文章创建成功！")
        return super().form_valid(form)
    
    def get_success_url(self):
        return reverse_lazy("article_admin_list")


# 文章浏览量更新视图
@method_decorator(csrf_exempt, name='dispatch')
class ArticleUpdateViewCountView(View):
    def post(self, request, pk):
        try:
            article = Article.objects.get(id=pk)
            article.view_count += 1
            article.save()
            return JsonResponse({'success': True, 'view_count': article.view_count})
        except Article.DoesNotExist:
            return JsonResponse({'success': False, 'error': '文章不存在'})
        except Exception as e:
            return JsonResponse({'success': False, 'error': str(e)})


# 更新文章视图
class ArticleUpdateView(LoginRequiredMixin, UpdateView):
    model = Article
    template_name = "ip_analysis/article_form.html"
    fields = ["title", "slug", "summary", "content", "status", "tags", "is_sticky",
              "meta_title", "meta_description", "meta_keywords"]
    
    def form_valid(self, form):
        messages.success(self.request, "文章更新成功！")
        return super().form_valid(form)
    
    def get_success_url(self):
        return reverse_lazy("article_admin_list")


# 删除文章视图
class ArticleDeleteView(LoginRequiredMixin, DeleteView):
    model = Article
    template_name = "ip_analysis/article_confirm_delete.html"
    
    def delete(self, request, *args, **kwargs):
        messages.success(self.request, "文章删除成功！")
        return super().delete(request, *args, **kwargs)
    
    def get_success_url(self):
        return reverse_lazy("article_admin_list")


# 文章批量操作视图
class ArticleBatchActionView(LoginRequiredMixin, View):
    def post(self, request):
        article_ids = request.POST.getlist("article_ids")
        action = request.POST.get("action")
        
        if not article_ids:
            messages.error(request, "请选择要操作的文章！")
            return redirect("article_admin_list")
        
        articles = Article.objects.filter(id__in=article_ids)
        
        if action == "publish":
            articles.update(status="published", publish_date=timezone.now())
            messages.success(request, f"成功发布 {len(article_ids)} 篇文章！")
        elif action == "draft":
            articles.update(status="draft")
            messages.success(request, f"成功设为草稿 {len(article_ids)} 篇文章！")
        elif action == "offline":
            articles.update(status="offline", publish_date=None)
            messages.success(request, f"成功下架 {len(article_ids)} 篇文章！")
        elif action == "delete":
            articles.delete()
            messages.success(request, f"成功删除 {len(article_ids)} 篇文章！")
        else:
            messages.error(request, "无效的操作！")
        
        return redirect("article_admin_list")


# 获取所有活跃标签
def get_active_tags(request):
    tags = Tag.objects.filter(is_active=True)
    return render(request, "ip_analysis/tags_list.html", {"tags": tags})